package com.hhit.zhgd.service.impl

import cn.dev33.satoken.stp.StpUtil
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.hhit.zhgd.dao.AdminMapper
import com.hhit.zhgd.domain.entity.Admin
import com.hhit.zhgd.domain.entity.LoginLog
import com.hhit.zhgd.service.AdminService
import com.hhit.zhgd.service.LoginLogService
import com.hhit.zhgd.service.MenuService
import com.hhit.zhgd.service.RoleService
import com.hhit.zhgd.utils.strToIntArr
import com.hhit.zhgd.utils.toIntArr
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import org.springframework.util.DigestUtils
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

@Service("adminService")
class AdminServiceImpl : ServiceImpl<AdminMapper, Admin>(), AdminService {
    @Autowired
    private val roleService: RoleService? = null

    @Autowired
    private val menuService: MenuService? = null

    @Autowired
    private val loginLogService: LoginLogService? = null

    override fun getList(page: Page<*>, params: HashMap<String, *>): Page<HashMap<String, *>> =
        this.baseMapper.getList(page, params)

    @Transactional(rollbackFor = [Exception::class], propagation = Propagation.SUPPORTS)
    override fun checkLogin(params: HashMap<String, *>): HashMap<String, *> {
        val result = HashMap<String, Any>()
        result["status"] = false

        val info = baseMapper.getInfo(params)
        if (info == null || info["status"] == 0) {
            result["message"] = "登录失败"
            return result
        }
        if (DigestUtils.md5DigestAsHex((params["password"].toString() + info["safe"].toString()).toByteArray()) != info["password"]) {
            result["message"] = "密码错误"
            return result
        }

        val params = HashMap<String, Any>()
        params["status"] = 1
        params["role_ids"] = info["role"].toString().toIntArr()
        val roleList = roleService?.getAll(params)
        if (roleList == null || roleList?.size == 0) {
            result["message"] = "登录失败"
            return result
        }

        //登录
        StpUtil.login(info["id"])

        // 更新登录信息
        updateLogin(java.lang.Long.valueOf(info["id"].toString()), params["ip"].toString())

        val data: HashMap<String, Any> = HashMap()
        data["avatar"] = info["avatar"].toString()
        data["username"] = info["username"].toString()
        data["token"] = StpUtil.getTokenValue()
        result["data"] = data
        result["status"] = true

        return result
    }

    override fun getInfo(params: HashMap<String, *>): HashMap<String, *> = this.baseMapper.getInfo(params)

    override fun getRoleAdminAll(roleId: Int): List<HashMap<String, *>> = this.baseMapper.getRoleAdminAll(roleId)
    override fun getPermissionList(adminId: Int): List<HashMap<String, Any?>>? {
        val list = ArrayList<HashMap<String, Any?>>()
        val admin = getById(adminId)

        val params = HashMap<String,Any?>()
        params["status"] = 1
        params["role_ids"]= admin.role?.toIntArr()
        val roles = roleService?.getAll(params)
        val menuIds = ArrayList<Int>()
        var root = 0;
        roles?.forEach { role->
            if (role.root==1) {
                root = 1
                return@forEach
            }
            role.permission?.toIntArr()?.forEach { menuIds.add(it) }
        }
        if (root==0 && menuIds.size==0) {
            return list
        }

        val query = HashMap<String,Any?>()
        query["status"] = 1
        if (root==0) {
            query["menu_ids"] = menuIds
        }
        val menus: List<HashMap<String, Any?>>? = menuService?.getAll(query)
        return menus
    }


    private fun updateLogin(id: Long, ip: String) {
        val update = Admin(id = id, loginIp = ip, loginTime = Date(), updateTime = Date())
        baseMapper.updateById(update)
        val log = LoginLog(adminId = id, loginIp = ip, createTime = Date())
        loginLogService?.save(log)
    }
}